<template>
    <el-form :inline="true" class="cmforminline" :model="mediaFormData" :rules="rules" label-width="120px"
        ref="createFormRef" label-position="right">
        <div class="cmitem">
            <el-form-item prop="mediatype" label="媒体类型">
                <el-select v-model="mediaFormData.mediatype" @change="getMediaTpl" placeholder="请选择媒类型"
                    :disabled="mediaid != undefined ? true : false">
                    <el-option v-for="item, index in createMediaShowTypes" :key="index" :label="item" :value="index">
                        {{ item }}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="tplid" label="媒体模板">
                <el-select v-model="mediaFormData.tplid" placeholder="请选择媒类型"
                    :disabled="mediaid != undefined ? true : false">
                    <el-option v-for="item, index in mediaTplKeyValue" :key="index" :label="item" :value="index">{{ item
                        }}
                    </el-option>
                </el-select>
            </el-form-item>
        </div>
        <!-- <div class="form-tips">请优先选择媒体类型，根据媒体类型和媒体模板的不同，需要添加的媒体字段也有所不同</div>-->
        <el-divider></el-divider>
        <!--媒体公共字段-->
        <div class="cmitem">
            <el-form-item label="媒体名称" prop="name">
                <el-input v-model="mediaFormData.name" placeholder="请输入媒体名称"></el-input>
            </el-form-item>
            <el-form-item label="媒体英文名称" prop="enname">
                <el-input v-model="mediaFormData.enname" placeholder="请输入媒体英文名称"></el-input>
            </el-form-item>
            <el-form-item label="别名" prop="alias">
                <el-input v-model="mediaFormData.alias" placeholder="请输入别名"></el-input>
            </el-form-item>
            <el-form-item prop="catid" label="一级分类">
                <el-select v-model="mediaFormData.catid" placeholder="请选择一级分类" @change="getSubCategory">
                    <el-option v-for="item in categoryData" :key="item.catid" :label="item.name" :value="item.catid">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="subcatids" label="二级分类">
                <el-select multiple v-model="mediaFormData.subcatids" placeholder="请选择二级分类">
                    <el-option v-for="item in subCategoryData" :key="item.subcatid" :label="item.name"
                        :value="item.subcatid">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="tags" label="标签">
                <el-select v-model="mediaFormData.tags" multiple filterable allow-create default-first-option
                    :reserve-keyword="false" placeholder="请选择标签">
                    <el-option v-for="item in tagsData" :key="item.id" :label="item.name" :value="item.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="cpid" label="内容提供方">
                <el-select v-model="mediaFormData.cpid" placeholder="请选择内容提供方" @change="handleCpChange" clearable
                    @clear="handleClear('cp')" :disabled="cpidDisabled">
                    <el-option v-for="item in mediaCpList" :key="item.cpid" :label="item.name" :value="item.cpid">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="来源ID" prop="sourceid">
                <el-input v-model="mediaFormData.sourceid" placeholder="请输入来源ID" :disabled="sourceidDisabled">
                </el-input>
            </el-form-item>
            <el-form-item prop="pubtime" label="发布时间">
                <el-date-picker v-model="mediaFormData.pubtime" type="datetime" placeholder="请选择日期和时间"
                    format="YYYY-MM-DD HH:mm:ss" @change="handleDateChange" />
            </el-form-item>
            <el-form-item v-if="mediaFormData.mediatype == 'liveroom'" prop="abstract" label="直播间简介" class="txtareabox">
                <el-input v-model="mediaFormData.abstract" maxlength="255" show-word-limit type="textarea"
                    placeholder="请输入直播间简介"></el-input>
            </el-form-item>
            <el-form-item v-else prop="abstract" label="媒资简介" class="txtareabox">
                <el-input v-model="mediaFormData.abstract" maxlength="255" show-word-limit type="textarea"
                    placeholder="请输入媒资简介"></el-input>
            </el-form-item>
            <el-form-item v-if="mediaFormData.mediatype == 'liveroom'" prop="content" label="直播间详情" class="txtareabox">
                <el-input v-model="mediaFormData.content" type="textarea" placeholder="请输入直播间详情"></el-input>
            </el-form-item>
            <el-form-item v-else-if="mediaFormData.mediatype != 'article'" prop="content" label="媒资详情"
                class="txtareabox">
                <el-input v-model="mediaFormData.content" type="textarea" placeholder="请输入媒资详情"></el-input>
            </el-form-item>
            <el-form-item v-else label="媒资详情" class="txtareabox">
                <Ckeditor :contentVal="ckeditorVal"></Ckeditor>
            </el-form-item>
            <media-pay :mediaFormPayData="mediaFormData"></media-pay>
        </div>
        <!-- <div class="form-tips">本文本块的字段内容，不会随着媒体类型和媒体模板的改变而改变</div>-->
        <el-divider></el-divider>
        <!--媒体动态字段-->
        <component :is="asyncComponentName" :formData="mediaFormExtendsData" />
        <!-- <div class="form-tips">本文本块的字段内容，会随着媒体类型和媒体模板的变化而增减</div> -->
        <el-divider v-if="mediaFormData.mediatype != 'liveroom'"></el-divider>
        <!--媒体缩略图-->
        <media-thumb :formData="mediaFormThumbData" v-if="mediaid == undefined" />
        <!-- <div class="form-tips">图片上传，最多允许上传2张图片</div>-->
        <!--<el-divider></el-divider> -->
        <el-row justify="center">
            <el-button type="primary" @click="handleMediaSubmit">保存</el-button>
        </el-row>
    </el-form>
</template>

<script>
import { ref, reactive, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex'
import { getTplData } from "@/api/media/mediatype";
import mediaTypeMixin from "@/mixins/mediaTypeMixin";
import MediaThumb from './components/EditExtends/MediaThumb'
import { mediaImageUpload } from '@/api/media/uploadimage'
import { getMediaInfo, createMedia, editMedia } from "@/api/media/media"
import { getGoodsBatchInfo } from "@/api/media/goods"
import { getCps } from "@/api/cp"
import { ElMessage } from 'element-plus'
import { getCategories, getSubCategories, getTags } from '@/api/media/constant'
import Ckeditor from './components/EditExtends/Ckeditor'
import MediaPay from './components/MediaPay'
export default {
    name: "",
    components: {
        ElMessage,
        Ckeditor,
        MediaThumb,
        "longvideo": defineAsyncComponent(() => import('./components/EditExtends/LongVideo')),
        "shortvideo": defineAsyncComponent(() => import('./components/EditExtends/ShortVideo')),
        "mediaarticle": defineAsyncComponent(() => import('./components/EditExtends/Article')),
        "imageset": defineAsyncComponent(() => import('./components/EditExtends/ImageSet')),
        "liveroom": defineAsyncComponent(() => import('./components/EditExtends/LiveRoom')),
        MediaPay
    },
    setup() {
        const store = useStore()
        const route = useRoute()
        const router = useRouter()
        const mediacorpid = store.getters.corpinfo.corpid
        const mediasubid = store.getters.subinfo.subid
        const mediauid = store.getters.userinfo.uid
        let groupid = route.query.groupid
        const mediaid = route.query.mediaid
        const asyncComponentName = ref('')

        // 媒体类型
        const { createMediaShowTypes } = mediaTypeMixin()

        //const createMediaShowTypes = ref({"longvideo":"长视频","shortvideo":"短视频","imageset":"图集","article":"文章资讯"})
        const mediaTplKeyValue = ref({})
        const mediaFormExtendsData = ref({})
        const mediaFormThumbData = ref([])
        const ckeditorVal = reactive({ content: null })
        // 一级分类获取方法mediaFormData.value.mediatype
        const getCategory = (mediatype) => {
            getCategories({ mediatype: mediatype, pagesize: 1000 }).then(response => {
                if (response.errcode == 0) {
                    categoryData.value = response.data.list
                    mediaFormData.value.catid = categoryData.value[0].catid
                    /*if( mediatype == 'liveroom' ){
                        mediaFormData.value.catid = 86
                    }else{
                        mediaFormData.value.catid = categoryData.value[0].catid
                    }*/
                } else {
                    console.log(response)
                }
            })
        }
        const getMediaTpl = () => {
            // 扩展字段内容置空
            if (mediaFormData.value.mediatype == 'imageset') {
                mediaFormExtendsData.value.imageSet = []
            } else {
                mediaFormExtendsData.value = {}
            }
            mediaFormThumbData.value.thumb = []
            // 根据媒体类型异步加载组件
            asyncComponentName.value = (mediaFormData.value.mediatype == 'article' ? 'mediaarticle' : mediaFormData.value.mediatype)
            console.log(asyncComponentName.value)
            mediaTplKeyValue.value = {};
            getTplData({ pagesize: 200, mediatype: mediaFormData.value.mediatype }).then(response => {
                response.data.forEach((tplData, index) => {
                    // console.log(tplData)
                    if (index == 0) {
                        mediaFormData.value.tplid = tplData.tplid
                    }
                    mediaTplKeyValue.value[tplData.tplid] = tplData.name
                })
            })
            getCategory(mediaFormData.value.mediatype)
        }

        // 内容提供方
        const cpidDisabled = ref(false)
        const sourceidDisabled = ref(true)
        const mediaCpList = ref([])
        getCps({ pagesize: 1000 }).then(response => {
            if (response.errcode == 0) {
                mediaCpList.value = response.data.list
            } else {
                console.log(response)
            }
        })
        const handleCpChange = () => {
            mediaFormData.value.sourceid = ''
            sourceidDisabled.value = false
        }
        const handleClear = (clearname) => {
            switch (clearname) {
                case 'cp':
                    sourceidDisabled.value = true
                    mediaFormData.value.sourceid = ''
                    break
            }
        }
        // 表单数据
        const createFormRef = ref(null)
        const rules = reactive({
            mediatype: { required: true, message: '请选择媒体类型', trigger: 'change' },
            tplid: { required: true, message: '请选择媒体模板', trigger: 'change' },
            name: { required: true, message: '请输入媒体名称', trigger: 'blur' },
            catid: { required: true, message: '请选择一级分类', trigger: 'change' },
            //subcatid: {required: true, message: '请选择二级分类', trigger: 'change'},
        })

        const formatDateTime = (dateTime) => {
            let date = dateTime.getDate();
            let month = dateTime.getMonth() + 1; // 月份从0开始，需要+1
            let year = dateTime.getFullYear();
            let hours = dateTime.getHours();
            let minutes = dateTime.getMinutes();
            let seconds = dateTime.getSeconds();

            // 使用padStart确保月份、日期、小时、分钟和秒总是两位数
            month = month.toString().padStart(2, '0');
            date = date.toString().padStart(2, '0');
            hours = hours.toString().padStart(2, '0');
            minutes = minutes.toString().padStart(2, '0');
            seconds = seconds.toString().padStart(2, '0');

            // 拼接成 "年月日 时:分:秒" 的格式
            return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
        }

        const mediaFormData = ref({
            'groupid': parseInt(groupid),
            'mediatype': null,
            'tplid': null,
            'pubtime': formatDateTime(new Date()), // 发布时间
        })

        const handleDateChange = (value) => {
            mediaFormData.value.pubtime = formatDateTime(value);
        }



        if (mediaid == undefined) {
            // mediaFormData.value.mediatype = 'longvideo'
            // mediaFormData.value.tplid = '5f80217524ac4'
            mediaFormData.value.mediatype = route.query.mediatype != undefined && route.query.mediatype != '' ? route.query.mediatype : 'liveroom'
            // mediaFormData.value.tplid = '2475db328ed111ecbf9200163e30b2e1'
        } else {
            mediaFormData.value.mediatype = route.query.mediatype
            mediaFormData.value.mediaid = mediaid
        }
        getMediaTpl()
        // router.go(-1)
        // console.log(router)
        const handleMediaSubmitaaaaa = () => {
            if (mediaFormData.value.mediatype == 'imageset' && mediaFormData.value.extends.item == undefined) {
                return
            }
            createFormRef.value.validate(valid => {
                if (valid) {
                    console.log(mediaFormData.value)
                    switch (mediaFormData.value.mediatype) {
                        case 'longvideo':
                            mediaFormData.value.extends.releaseyear = parseInt(mediaFormData.value.extends.releaseyear)
                            break;
                    }
                    if (mediaid != undefined) {
                        console.log('1111')
                        editMedia(mediaFormData.value).then(response => {
                            if (response.errcode == 0) {
                                ElMessage({ type: 'success', message: '更新成功', duration: 2000 })
                                setTimeout(function () {
                                    let routerPushName = 'medialist'
                                    if (router.currentRoute.value.name != 'editmedia') {
                                        routerPushName = 'mediaslist'
                                        routerPushName += (route.query.isall != undefined && route.query.isall == '1' ? 'all' : route.query.mediatype)
                                        router.push({ name: routerPushName })
                                    } else {
                                        router.push({ name: routerPushName, query: { groupid: groupid } })
                                    }
                                }, 2000)
                            } else {
                                console.log(response)
                            }
                        })
                    } else {
                        createMedia(mediaFormData.value).then(response => {
                            if (response.errcode == 0) {
                                ElMessage({ type: 'success', message: '添加成功', duration: 2000 })
                                setTimeout(function () {
                                    let routerPushName = 'medialist'
                                    if (router.currentRoute.value.name != 'createmedia') {
                                        routerPushName = 'mediaslist'
                                        routerPushName += (route.query.mediatype != undefined && route.query.mediatype != '' ? route.query.mediatype : 'all')
                                        router.push({ name: routerPushName })
                                    } else {
                                        router.push({ name: routerPushName, query: { groupid: groupid } })
                                    }
                                    //router.push({name:'medialist',query: {groupid:groupid}})
                                }, 2000)
                            } else {
                                console.log(response)
                            }
                        })
                    }
                } else {
                    ElMessage({ type: 'warning', message: '请填写必填字段', duration: 2000 })
                }
            })
        }
        const handleMediaSubmit = () => {
            if (mediaFormData.value.paytype != undefined && mediaFormData.value.paytype == "1") {
                try {

                    let numRegF = /^[0-9.]*$/
                    let numReF = new RegExp(numRegF)

                    let numReg = /^[0-9]*$/
                    let numRe = new RegExp(numReg)
                    mediaFormData.value.prices.forEach(function (val, index) {
                        if (val.name == undefined || val.name == '') {
                            throw new Error('套餐' + (index + 1) + '的套餐名称为必填字段')
                        }
                        if (val.oprice == undefined || val.oprice == '') {
                            throw new Error('套餐' + (index + 1) + '的原价为必填字段')
                        }
                        if (val.days == undefined || val.days == '') {
                            throw new Error('套餐' + (index + 1) + '的套餐天数为必填字段')
                        }
                        if (!numReF.test(val.oprice)) {
                            throw new Error('套餐' + (index + 1) + '的原价填写错误')
                        }
                        if (!numRe.test(val.days)) {
                            throw new Error('套餐' + (index + 1) + '的套餐天数填写错误，必须为数字')
                        }
                        if (val.pprice != undefined && val.pprice != '' && !numReF.test(val.pprice)) {
                            throw new Error('套餐' + (index + 1) + '的促销价填写错误')
                        }
                    })
                } catch (e) {
                    ElMessage({ type: 'error', message: e.message, duration: 2000 })
                    return false
                }
            }

            Promise.all([getMediaSubmitData(mediaFormData.value, mediaFormExtendsData.value), thumbUpload(mediaFormData.value, mediaFormThumbData.value)]).then((result) => {
                if (result.length > 0) {
                    let success = 0
                    result.forEach(function (val) {
                        if (val == 'success') {
                            success++
                        }
                    })
                    if (success == result.length) {
                        handleMediaSubmitaaaaa()
                    } else {
                        ElMessage({ type: 'warning', message: '表单上传数据错误', duration: 2000 })
                    }
                } else {
                    ElMessage({ type: 'warning', message: '表单上传数据错误', duration: 2000 })
                }
            })
        }
        function thumbUpload(mediaFormData, mediaFormThumbData) {
            // 海报图片上传--start
            return new Promise((resolve, reject) => {
                let promiseData = []
                let imgData = []
                Object.keys(mediaFormThumbData).forEach(function (key) {
                    // console.log(uploadImgObj[key].length)
                    if (mediaFormThumbData[key].length > 0) {
                        mediaFormThumbData[key].forEach(function (imgInfo) {
                            if (imgInfo.raw != undefined) {
                                let uploadData = new FormData()
                                uploadData.append("corpid", mediacorpid)
                                uploadData.append("subid", mediasubid)
                                uploadData.append("uid", mediauid)
                                uploadData.append("groupid", groupid)
                                uploadData.append("isself", 1)
                                uploadData.append("upfile", imgInfo.raw)
                                promiseData.push(mediaImageUpload(uploadData))
                                imgData.push(null)
                            } else {
                                imgData.push(imgInfo.imgid)
                            }
                            /*mediaImageUpload(uploadData).then(response => {
                                if( response.errcode == 0 ){
                                    imgData[key].push(response.data.imgid)
                                }else{
                                    console.log(response)
                                }
                            })*/
                        })
                    }
                })
                mediaFormData.imgids = [];
                if (promiseData.length > 0) {
                    Promise.all(promiseData).then((result) => {
                        console.log(result)
                        let success = 0
                        if (result.length > 0) {
                            result.forEach(function (val) {
                                if (val.errcode == 0) {
                                    try {
                                        imgData.forEach(function (imgVal, imgKey) {
                                            if (imgVal == null) {
                                                imgData[imgKey] = val.data.imgid
                                                success++
                                                throw new Error()
                                            }
                                        })
                                    } catch (err) {
                                        console.log()
                                    }
                                }
                            })
                        }
                        if (success == result.length) {
                            mediaFormData.imgids = imgData
                            console.log(mediaFormData.imgids)
                            resolve('success')
                        } else {
                            reject('fail')
                        }
                    })
                } else {
                    //mediaFormData.imgids = imgData['thumb'] !== undefined ? imgData['thumb'] : [];
                    mediaFormData.imgids = imgData
                    resolve('success')
                }

            })
            // 海报图片上传--end
        }
        function getMediaSubmitData(mediaFormData, mediaFormExtendsData) {
            return new Promise((resolve, reject) => {
                let promiseData = []
                mediaFormData.extends = {}
                if (mediaFormData.mediatype == 'longvideo') {
                    mediaFormData.hasseries = mediaFormExtendsData.hasseries
                    mediaFormData.extends.person = {}
                    mediaFormData.extends.person.star = mediaFormExtendsData.star,
                        mediaFormData.extends.person.director = mediaFormExtendsData.director
                    mediaFormData.extends.person.screenwriter = mediaFormExtendsData.screenwriter
                    delete mediaFormExtendsData.star, mediaFormExtendsData.director, mediaFormExtendsData.screenwriter, mediaFormExtendsData.hasseries
                    Object.assign(mediaFormData.extends, mediaFormExtendsData)
                } else if (mediaFormData.mediatype == 'imageset') {
                    let imgMsg = ''
                    Object.keys(mediaFormExtendsData.imageSet).forEach(function (key) {
                        if (imgMsg !== '') {
                            return
                        } else {
                            if (!mediaFormExtendsData.imageSet[key].itemtitle) {
                                key = parseInt(key) + 1
                                imgMsg = '图集' + key + '标题不能为空'
                            } else if (!mediaFormExtendsData.imageSet[key].itemdesc) {
                                key = parseInt(key) + 1
                                imgMsg = '图集' + key + '描述不能为空'
                            } else if (!mediaFormExtendsData.imageSet[key].imgid) {
                                key = parseInt(key) + 1
                                imgMsg = '图集' + key + '图片不能为空'
                            }
                        }
                    })
                    if (imgMsg !== '') {
                        mediaFormData.extends.item = undefined
                        ElMessage({ type: 'warning', message: imgMsg, duration: 2000 })
                        return
                    }
                    mediaFormData.extends.item = []
                    Object.keys(mediaFormExtendsData.imageSet).forEach(function (key) {
                        if (mediaFormData.extends.item == undefined) {
                            return
                        }
                        let itemInfo = { title: null, desc: null, image: null }
                        itemInfo.title = mediaFormExtendsData.imageSet[key].itemtitle
                        itemInfo.desc = mediaFormExtendsData.imageSet[key].itemdesc
                        itemInfo.image = mediaFormExtendsData.imageSet[key].imgid

                        /*if( mediaFormExtendsData.imageSet[key].imageInfo.raw == undefined ){
                            itemInfo.code = mediaFormExtendsData.imageSet[key].code
                        }else{
                            let uploadData = new FormData()
                            uploadData.append("corpid", mediacorpid)
                            uploadData.append("subid", mediasubid)
                            uploadData.append("uid", mediauid)
                            uploadData.append("groupid", groupid)
                            uploadData.append("upfile", mediaFormExtendsData.imageSet[key].imageInfo.raw)
                            promiseData.push(cloudstorageImageUpload(uploadData))
                        }*/
                        mediaFormData.extends.item.push(itemInfo)
                        /*cloudstorageImageUpload(uploadData).then(response => {
                            console.log(response.data)
                            if( response.errcode == 0 ){
                                itemInfo.code = response.data.sourceid
                                mediaFormData.extends.item.push(itemInfo)
                            }else{
                                mediaFormData.extends.item = undefined
                                console.log(response)
                            }
                        })*/
                    })
                } else if (mediaFormData.mediatype == 'article') {
                    mediaFormData.content = ckeditorVal.content
                    Object.assign(mediaFormData.extends, mediaFormExtendsData.goodsids)
                } else if (mediaFormData.mediatype == 'liveroom') {
                    mediaFormData.hasseries = 1
                    mediaFormData.goodsids = mediaFormExtendsData.goodsids
                    Object.assign(mediaFormData.extends, mediaFormExtendsData)
                } else {
                    Object.assign(mediaFormData.extends, mediaFormExtendsData)
                }
                mediaFormData.corpid = mediacorpid
                mediaFormData.subid = mediasubid
                mediaFormData.uid = mediauid
                if (promiseData.length > 0) {
                    Promise.all(promiseData).then((result) => {
                        let success = 0
                        if (result.length > 0) {
                            result.forEach(function (val) {
                                if (val.errcode == 0) {
                                    try {
                                        mediaFormData.extends.item.forEach(function (itemVal, itemKey) {
                                            if (itemVal.code == null) {
                                                mediaFormData.extends.item[itemKey].code = val.data.sourceid
                                                success++
                                                throw new Error()
                                            }
                                        })
                                    } catch (err) {
                                        console.log()
                                    }
                                }
                            })
                        }
                        if (success == result.length) {
                            resolve('success')
                        } else {
                            reject('fail')
                        }
                    })
                } else {
                    resolve('success')
                }
            })
        }

        // 编辑相关
        function mediaInfoToForm(mediaInfoData) {
            if (mediaInfoData.cpid) {
                sourceidDisabled.value = false
            }
            groupid = mediaInfoData.groupid
            mediaFormData.value.mediatype = mediaInfoData.mediatype
            mediaFormData.value.tplid = mediaInfoData.tplid
            mediaFormData.value.name = mediaInfoData.name
            mediaFormData.value.enname = mediaInfoData.enname
            mediaFormData.value.alias = mediaInfoData.alias
            mediaFormData.value.catid = mediaInfoData.catid
            mediaFormData.value.subcatids = mediaInfoData.subcatids
            mediaFormData.value.tags = mediaInfoData.tags
            mediaFormData.value.cpid = mediaInfoData.cpid
            mediaFormData.value.sourceid = mediaInfoData.sourceid
            mediaFormData.value.abstract = mediaInfoData.abstract
            mediaFormData.value.pubtime = mediaInfoData.pubtime
            if (mediaInfoData.mediatype == 'article') {
                ckeditorVal.content = mediaInfoData.content
            } else {
                mediaFormData.value.content = mediaInfoData.content
            }
            Object.assign(mediaFormExtendsData.value, mediaInfoData.extends)
            if (mediaInfoData.mediatype == 'longvideo') {
                delete mediaFormExtendsData.value.person
                Object.assign(mediaFormExtendsData.value, mediaInfoData.extends.person)
                mediaFormExtendsData.value.releaseyear = mediaFormExtendsData.value.releaseyear + ''
                mediaFormExtendsData.value.hasseries = mediaInfoData.hasseries
                mediaFormExtendsData.value.mediaid = mediaid
            } else if (mediaInfoData.mediatype == 'imageset') {
                mediaFormExtendsData.value.imageSet = []
                if (mediaInfoData.extends.item.length > 0) {
                    mediaInfoData.extends.item.forEach(function (val) {
                        let setData = {}
                        setData.itemtitle = val.title
                        setData.itemdesc = val.desc
                        setData.imgid = val.image.imgid
                        setData.imageUrl = val.image.viewurl
                        mediaFormExtendsData.value.imageSet.push(setData)
                    })
                    // console.log('create', mediaFormExtendsData.value.imageSet)
                }
            } else if (mediaInfoData.mediatype == 'liveroom') {
                Object.assign(mediaFormExtendsData.value, mediaInfoData.extends)
                mediaFormExtendsData.value.mediaid = mediaInfoData.mediaid
                // mediaFormExtendsData.value.goodsid = [1000006,1000005]
                if (mediaInfoData.goodss != undefined && mediaInfoData.goodss.length > 0) {
                    mediaFormExtendsData.value.goodsids = []
                    mediaInfoData.goodss.forEach(goodsInfo => {
                        mediaFormExtendsData.value.goodsids.push(goodsInfo.goodsid)
                    })
                    mediaFormExtendsData.value.goodsList = []
                    let query = {}
                    query['goods_id'] = mediaFormExtendsData.value.goodsids.join(',')
                    console.log(query)
                    getGoodsBatchInfo(query).then(response => {
                        let goodsList = []
                        if (response.errcode == 0 && response.data.length > 0) {
                            response.data.forEach(goodsInfo => {
                                goodsList[goodsInfo.goods_id] = goodsInfo
                            })
                            mediaFormExtendsData.value.goodsids.forEach(goodsId => {
                                mediaFormExtendsData.value.goodsList.push(goodsList[goodsId])
                            })
                        } else {
                            console.log(response)
                        }
                    })
                }
            } else {
                Object.assign(mediaFormExtendsData.value, mediaInfoData.extends)
            }
            mediaFormThumbData.value.thumb = []
            if (mediaInfoData.thumbs.length > 0) {
                mediaInfoData.thumbs.forEach(function (val) {
                    let thumbImgInfo = { name: null, imgid: null, url: null }
                    thumbImgInfo.name = val.name
                    thumbImgInfo.imgid = val.imgid
                    thumbImgInfo.url = val.viewurl
                    thumbImgInfo.layout = ''
                    mediaFormThumbData.value.thumb.push(thumbImgInfo)
                })
            }
        }
        const categoryData = ref([])
        const subCategoryData = ref([])
        const tagsData = ref([])
        getTags({ pagesize: 1000 }).then(response => {
            if (response.errcode == 0) {
                tagsData.value = response.data.list
            } else {
                console.log(response)
            }
        })
        // 获取二级分类方法
        const getSubCategory = (catid) => {
            getSubCategories({ catid: catid, pagesize: 1000 }).then(response => {
                if (response.errcode == 0) {
                    mediaFormData.value.subcatids = []
                    subCategoryData.value = response.data.list
                } else {
                    console.log(response)
                }
            })
        }
        // getCategory(mediaFormData.value.mediatype)
        if (mediaid) {
            getMediaInfo({ mediaid: mediaid, corpid: mediacorpid }).then(response => {
                if (response.errcode == 0) {
                    //mediaInfoData.value = response.data
                    //tplid.value = mediaInfoData.value.tplid
                    mediaInfoToForm(response.data)
                    getSubCategories({ catid: mediaFormData.value.catid, pagesize: 1000 }).then(response => {
                        if (response.errcode == 0) {
                            subCategoryData.value = response.data.list
                        } else {
                            console.log(response)
                        }
                    })
                } else {
                    console.log(response)
                    ElMessage({ type: 'error', message: '媒资详情数据获取失败', duration: 2000 })
                }
            })
        }

        return {
            handleDateChange,
            asyncComponentName,
            createMediaShowTypes,
            mediaTplKeyValue,
            getMediaTpl,
            cpidDisabled,
            sourceidDisabled,
            mediaCpList,
            handleCpChange,
            handleClear,
            createFormRef,
            rules,
            mediaFormData,
            mediaFormExtendsData,
            mediaFormThumbData,
            handleMediaSubmit,
            mediaid,
            categoryData,
            subCategoryData,
            tagsData,
            getSubCategory,
            ckeditorVal
        }
    }
}
</script>

<style lang="scss">
.cmforminline {
    margin-right: 20px;

    .el-form-item {
        width: 32%;
        margin-right: 2%;
        margin-bottom: 18px;
        // .el-form-item__content{
        //      line-height: 36px;
        //     .el-input{
        //         .el-input__inner{
        //             height: 36px !important;
        //             line-height: 36px !important;
        //         }
        //     }
        // }
    }

    .cmitem {
        .el-form-item:nth-child(3n) {
            margin-right: 0;
        }
    }

    .el-form-item__label {
        color: #999;
        line-height: 36px;
    }

    .el-form-item__content {
        min-width: 220px;

        .el-select {
            width: 100%;
        }

        .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
            width: 100%;
        }
    }

    .form-tips {
        padding-left: 10px;
        font-size: 12px;
        color: #ccc;
    }

    .el-divider--horizontal {
        margin: 0 0 15px;
    }

    .el-divider {
        border-top: 1px dashed #ddd;
        background-color: transparent;
    }

    .txtareabox {
        width: 100% !important;

        // margin-bottom:15px;
        .el-textarea__inner {
            height: 100px;
        }
    }
}

@media screen and (max-width:1200px) {
    .cmforminline {
        .el-form-item {
            width: 48%;
        }

        .cmitem {

            .el-form-item:nth-child(3n) {
                margin-right: 2%;
            }
        }
    }
}

@media screen and (max-width:768px) {
    .cmforminline {
        .el-form-item {
            width: 100%;
        }
    }
}

.ck.ck-editor__main {
    height: 400px;
}

.ck-content {
    height: 100%;
}
</style>